<template>
  <div class="pay-page">
    <!-- 顶部导航栏 -->
    <header class="header">
<!--      <div class="logo" @click="goHome">珍珍抢票系统</div>-->
<!--      <div class="location">北京</div>-->
<!--      <nav class="nav">-->
<!--        <a href="#" @click="goHome">首页</a>-->
<!--      </nav>-->
<!--      <div class="user-actions">-->
<!--        <el-button type="text">登录</el-button>-->
<!--      </div>-->
    </header>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading">加载中...</div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-container">
      <div class="error">{{ error }}</div>
      <el-button type="primary" @click="goBack">返回上一页</el-button>
    </div>

    <!-- 支付信息 -->
    <div v-if="!loading && !error" class="pay-container">
      <el-card class="pay-card">
        <h2 class="pay-title">确认订单信息</h2>

        <div class="order-info">
          <div class="info-item">
            <span class="info-label">演唱会名称：</span>
            <span class="info-value">{{ concert.title || '加载中...' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">艺人：</span>
            <span class="info-value">{{ concert.artist || '加载中...' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">演出时间：</span>
            <span class="info-value">{{ formatDate(concert.startdate) || '加载中...' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">演出场地：</span>
            <span class="info-value">{{ concert.venueName || '加载中...' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">座位区域：</span>
            <span class="info-value">{{ seatInfo.area || '加载中...' }}</span>
          </div>
          <el-button @click="refreshPrice">刷新价格</el-button>
          <!-- 核心修复：给seatPrice加安全判空，避免null调用toFixed -->
          <div class="info-item price-item">
            <span class="info-label">票价：</span>
<!--            <span class="info-value">¥{{ (seatPrice.value !== null && seatPrice.value !== undefined) ? seatPrice.value.toFixed(2) : '1.00' }}</span>-->
                <span class="info-value">¥{{seatPrice}}</span>
          </div>
        </div>

        <div class="pay-actions">
          <el-button
              type="primary"
              size="large"
              @click="submitPayment"
          >
            <span v-if="!isSubmitting">确认支付</span>
            <span v-if="isSubmitting">处理中...</span>
          </el-button>
          <el-button
              size="large"
              @click="goBack"
          >
            取消
          </el-button>
        </div>
      </el-card>
    </div>

    <Footer />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import Footer from "@/view/footer.vue";
import { ElMessage } from "element-plus";

// 路由和导航相关
const route = useRoute();
const router = useRouter();

// API客户端配置（统一添加请求拦截器，避免重复创建实例）
const createApiClient = (baseURL) => {
  const client = axios.create({
    baseURL,
    timeout: 10000,
  });
  // 请求拦截器：统一处理token（避免每个请求单独加）
  client.interceptors.request.use(config => {
    const token = localStorage.getItem('token') || '';
    if (token) {
      config.headers.token = token; // 匹配后端token接收字段
    }
    return config;
  }, error => {
    ElMessage.error('请求发送失败，请检查网络');
    return Promise.reject(error);
  });
  return client;
};

// 初始化两个API客户端（分别对应不同服务）
const apiClient = createApiClient('http://localhost:8089'); // 座位/价格服务
const apiClient1 = createApiClient('http://localhost:8085'); // 演唱会服务
const apiClient2 = createApiClient('http://localhost:8083');

// 响应式变量：初始化给seatPrice设为null，明确数据状态
const loading = ref(true);
const error = ref('');
const isSubmitting = ref(false);
const seatId = ref('');
const seatPrice = ref(null); // 初始设为null，避免undefined
const concert = ref({});
const seatInfo = ref({});


const refreshPrice = async () => {
  try {
    await fetchSeatPrice();
    ElMessage.success('价格刷新成功');
  } catch (error) {
    ElMessage.error('价格刷新失败');
  }
};

async function updateSeatCount() {
  try {
    // 获取座位最新信息
    const seatResponse = await apiClient.get(`/seat/getSeatById/${seatId.value}`);
    if (seatResponse.data && seatResponse.data.code === 200) {
      const seat = seatResponse.data.data;
      // 减少座位数量
      const updatedCount = (seat.count || 0) - 1;

      // 更新座位信息
      const updateResponse = await apiClient.put('/seat/edit', {
        id: seatId.value,
        count: updatedCount >= 0 ? updatedCount : 0
      });

      if (updateResponse.data && updateResponse.data.code === 200) {
        // ElMessage.success('座位数量更新成功');
      } else {
        ElMessage.warning('座位数量更新失败');
      }
    }
  } catch (error) {
    console.error('更新座位数量失败:', error);
    ElMessage.error('更新座位数量失败: ' + (error.message || '未知错误'));
  }
}




// 格式化日期：加空值判断，避免无效日期转换
const formatDate = (dateString) => {
  if (!dateString || typeof dateString !== 'string') return '';
  const date = new Date(dateString);
  return isNaN(date.getTime()) ? '' : date.toLocaleString();
};

// 获取座位价格信息：加数据格式校验，避免后端返回非数字
async function fetchSeatPrice() {
  try {
    console.log('座位ID:', seatId.value);
    const response = await apiClient.get(`/seatprice/getbyseatid/${seatId.value}`);
    console.log('座位价格接口返回数据:', response);
    // 校验接口返回格式
    if (!response.data || response.data.code !== 200) {
      throw new Error(response.data?.msg || '获取座位价格失败');
    }
    // 校验价格是否为有效数字
    console.log('wfdddddd:',response.data.data.price);
    const price = Number(response.data.data.price);
    seatPrice.value = isNaN(price) ? 0 : price; // 非数字则设为0
    console.log('座位价格:', seatPrice.value);
    console.log('OOOOOOO',seatPrice);
    return seatPrice.value;
  } catch (err) {
    console.error('获取座位价格失败:', err);
    error.value = err.message || '获取座位价格失败，请重试';
    ElMessage.error(error.value);
    seatPrice.value = 0; // 出错时设为0，避免页面报错
  }
}

// 获取座位详情：加数据容错，避免后端返回空对象
async function fetchSeatInfo() {
  try {
    const response = await apiClient.get(`/seat/getSeatById/${seatId.value}`);
    if (!response.data || response.data.code !== 200) {
      throw new Error(response.data?.msg || '获取座位信息失败');
    }
    seatInfo.value = response.data.data || {}; // 空数据则设为空对象
    return seatInfo.value;
  } catch (err) {
    console.error('获取座位信息失败:', err);
    error.value = err.message || '获取座位信息失败，请重试';
    ElMessage.error(error.value);
    seatInfo.value = {}; // 出错时设为空对象
  }
}


// 获取演唱会详情：同理加容错
async function fetchConcertDetail(concertId) {
  try {
    const response = await apiClient1.get(`/concert/getConcertById/${concertId}`);
    if (!response.data || response.data.code !== 200) {
      throw new Error(response.data?.msg || '获取演唱会信息失败');
    }
    concert.value = response.data.data || {}; // 空数据则设为空对象
    return concert.value;
  } catch (err) {
    console.error('获取演唱会信息失败:', err);
    error.value = err.message || '获取演唱会信息失败，请重试';
    ElMessage.error(error.value);
    concert.value = {}; // 出错时设为空对象
  }
}

// 初始化页面数据：优化错误捕获，避免单个接口失败导致整体卡死
async function initData() {
  try {
    loading.value = true;
    error.value = '';

    // 从路由参数获取并校验
    seatId.value = route.query.seatId || '';
    const concertId = route.params.id || '';

    if (!seatId.value || !concertId) {
      throw new Error('参数错误：缺少演唱会ID或座位ID');
    }

    // 并行请求：用Promise.allSettled避免单个接口失败影响其他
    const [seatRes, concertRes, priceRes] = await Promise.allSettled([
      fetchSeatInfo(),
      fetchConcertDetail(concertId),
      fetchSeatPrice()

    ]);

    // 检查是否有接口失败（仅收集错误，不阻断页面）
    const errors = [];
    if (seatRes.status === 'rejected') errors.push('座位信息加载失败');
    if (concertRes.status === 'rejected') errors.push('演唱会信息加载失败');
    if (priceRes.status === 'rejected') errors.push('票价信息加载失败');

    if (errors.length > 0) {
      error.value = errors.join('，');
      ElMessage.warning(error.value);
    }

  } catch (err) {
    console.error('初始化支付页面失败:', err);
    error.value = err.message || '加载支付信息失败，请重试';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
    console.log('initData 执行完毕，loading 设置为 false');
  }
}

// 提交支付：优化按钮禁用逻辑，避免无效点击
async function submitPayment() {
  // if (!seatId.value || seatPrice.value <= 0) {
  //   ElMessage.warning('座位或票价信息错误，无法支付');
  //   console.log('isSubmitting in finallyAAAAA:');
  //   return;
  // }

  try {
    isSubmitting.value = true;
    console.log('isSubmitting in finallyBBBBBBBB:');
    // 检查token（提前拦截，避免无效请求）
    const token = localStorage.getItem('token') || '';
    if (!token) {
      router.push({
        path: '/login',
        query: {redirect: route.fullPath}
      });
      ElMessage.warning('请先登录');
      return;
    }

    // 调用支付宝支付接口
    const response = await apiClient2.post(
        '/alipay/pay',
        {},
        {params: {seatId: seatId.value,
                        concertId: concert.value.id}} // 简化参数传递
    );

    // 处理支付宝表单（加格式校验）
    if (response.data && typeof response.data === 'string') {
      const div = document.createElement('div');
      div.innerHTML = response.data;
      document.body.appendChild(div);
      const form = div.querySelector('form');
      if (form) {
        form.submit();
      } else {
        throw new Error('支付宝支付表单格式错误');
      }
    } else {
      throw new Error('支付接口返回数据无效');
    }

  } catch (err) {
    console.error('发起支付失败:', err);
    ElMessage.error(err.message || '发起支付失败，请重试');
  } finally {
    console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
    isSubmitting.value = false;
    updateSeatCount();
  }
}

// 返回上一页：加防重复点击（可选优化）
function goBack() {
  if (!isSubmitting.value) {
    router.back();
  }
}

// 返回首页
function goHome() {
  if (!isSubmitting.value) {
    router.push({name: 'homepage'});
  }
}

// 页面挂载时初始化数据
onMounted(() => {
  initData();
});
</script>

<style scoped>
.pay-page {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  flex-wrap: wrap;
  gap: 10px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #ff6700;
  cursor: pointer;
}

.location,
.nav,
.user-actions {
  margin: 0 10px;
}

.nav a {
  margin: 0 5px;
  text-decoration: none;
  color: #333;
  padding: 5px;
  cursor: pointer;
}

.nav a:hover {
  color: #ff6700;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  padding: 50px 0;
}

.loading {
  font-size: 18px;
  color: #666;
}

.error {
  font-size: 18px;
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

/* 支付容器 */
.pay-container {
  flex: 1;
  padding: 30px 0;
  display: flex;
  justify-content: center;
}

.pay-card {
  width: 100%;
  max-width: 600px;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.pay-title {
  font-size: 22px;
  color: #333;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #ff6700;
}

/* 订单信息 */
.order-info {
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px dashed #eee;
  align-items: center;
}

.info-label {
  font-weight: bold;
  color: #666;
  width: 120px;
}

.info-value {
  color: #333;
  flex: 1;
}

.price-item {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 2px solid #f5f5f5;
}

.price-item .info-value {
  color: #ff6700;
  font-size: 18px;
  font-weight: bold;
}

/* 支付按钮区域 */
.pay-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.pay-actions .el-button {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .pay-card {
    padding: 20px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    margin-bottom: 5px;
  }

  .pay-actions {
    flex-direction: column;
  }
}
</style>